﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common;
using System.Reflection;
using GameServer.Servers;
namespace GameServer.Controller
{
    /// <summary>
    /// 控制器的管理器
    /// </summary>
    class ControllerManager
    {
        /// <summary>
        /// 放所有的控制器
        /// </summary>
        private Dictionary<RequestCode, BaseController> controllerDict = new Dictionary<RequestCode, BaseController>();
        /// <summary>
        /// 持有当前server的实例
        /// </summary>
        private Server server;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="server">当前的server的实例</param>
        public ControllerManager(Server server) {
            this.server = server;
            InitController();
        }

        /// <summary>
        /// 初始化所有的控制器
        /// </summary>
        void InitController()
        {
            DefaultController defaultController = new DefaultController();
            controllerDict.Add(defaultController.RequestCode, defaultController);
            controllerDict.Add(RequestCode.User, new UserController());
            controllerDict.Add(RequestCode.Room, new RoomController());
            controllerDict.Add(RequestCode.Game, new GameController());
        }

        /// <summary>
        /// 处理请求
        /// </summary>
        /// <param name="requestCode"></param>
        /// <param name="actionCode"></param>
        /// <param name="data"></param>
        /// <param name="client"></param>
        public void HandleRequest(RequestCode requestCode,ActionCode actionCode,string data,Client client)
        {
            BaseController controller;
            bool isGet = controllerDict.TryGetValue(requestCode, out controller);//从字典中找到requestCoad的控制器
            if (isGet == false)
            {
                Console.WriteLine("无法得到[" + requestCode + "]所对应的Controller,无法处理请求");return;
            }
            string methodName = Enum.GetName(typeof(ActionCode), actionCode);//得到actionCoad对应的方法名
            //反射
            MethodInfo mi = controller.GetType().GetMethod(methodName);//检查controller里面有没有methodName所对应的方法
            if (mi == null)
            {
                Console.WriteLine("[警告]在Controller["+controller.GetType()+"]中没有对应的处理方法:["+methodName+"]");return;
            }
            object[] parameters = new object[] { data,client,server };//准备好方法所用的参数
            object o = mi.Invoke(controller, parameters);//执行方法
            if(o==null||string.IsNullOrEmpty( o as string))
            {
                return;
            }
            server.SendResponse(client, actionCode, o as string);
        }

    }
}
